package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserService apUserService;

    /**
     * 调用外部服务
     */
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;



    /**
     * 查看审核信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findListByStatus(AuthDto dto) {
        //检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页，错误则初始化分页信息
        dto.checkParam();
        //开启分页
        IPage<ApUserRealname> page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper();

        //检查status是否存在,存在则添加条件
        if (dto.getStatus()!=null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //执行查询
        page = page(page,queryWrapper);

        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    /**
     * 审核实名认证并修改状态
     * @param dto
     * @param status  2 审核失败   9 审核成功
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //参数检查
        if (dto == null || dto.getStatus() == null || status == null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询真实信息
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId,dto.getId()));
        //检查用户真实信息是否存在
        if (apUserRealname == null) {
            log.error("apUserRealname is Null userRealnameId:{}",dto.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (apUserRealname.getStatus().intValue() != 1){
            log.error("apUserRealname is not wait userRealnameId:{}",dto.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //根据userId得到APP用户信息
        ApUser apUser = apUserService.getOne(Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId, apUserRealname.getUserId()));
        //判断APP用户是否存在
        if(apUser == null){
            log.error("apUserRealname apUser is Null userRealnameId:{}, userId:{} ", dto.getId(), apUserRealname.getUserId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //更新认证用户信息
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //认证状态如果为 通过
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //创建自媒体账户
            WmUser wmUser = createWmUser(dto,apUser);
            //创建作者信息
            createApAuthor(wmUser);
        }
        //更新APP用户状态
        apUser.setFlag((short) 1);
        apUserService.updateById(apUser);
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建作者信息
     * @param wmUser
     */
    private void createApAuthor(WmUser wmUser) {
        //检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(apAuthorResult.getCode().intValue() != 0){
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,apAuthorResult.getErrorMessage());
        }
        //检查作者信息是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        //添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2); // 自媒体用户类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);
        //失败，抛出异常
        if (result.getCode() != 0) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
    }

    /**
     *创建自媒体账户
     * @param dto
     * @param apUser app端用户
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public WmUser createWmUser(AuthDto dto, ApUser apUser) {
        //查询自媒体账号是否存在
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if(wmUserResult.getCode().intValue() != 0){
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        WmUser wmUser =wmUserResult.getData();
        if (wmUser != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"自媒体用户信息已存在");
        }
        //创建自媒体账号
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(saveResult.getCode().intValue()!=0){
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }
}
